<?php

namespace app\common\library;

use app\admin\model\Reserve;
use app\admin\model\Setting;
use app\common\model\Room;
use app\common\model\Third;
use Carbon\Carbon;
use fast\Http;
use fast\Random;
use think\Env;
use think\Log;

class Tongtongsuo
{
    public function test()
    {
        $clientId = Env::get('tongtongsuo.client_id');
        $clientSecret = Env::get('tongtongsuo.client_secret');
    }

    public function getAccessToken($userId)
    {
        $res = Third::where('user_id', $userId)->where('platform', Third::PLATFORM_TONGTONGSUO)->find();
        if (!$res) {
            return false;
        }
    }

    

    public function addPassword($lockId, $phone, $startDate, $endDate, $user)
    {
        $testPay = Env::get('common.test_pay');

        // 测试 
        if ($testPay) {
            return [
                'blue_key_id' => 'sdfsdf',
                'blue_lock_data' => 'sdfsdf',
                'rand_key_id' => 'wefwef',
                'rand_key_pwd' => 'wegwef',
            ];
        }
        //dev环境
//        $phone = '15719438520';
//        $userId = 456;

        //prod环境
        $phone = '18581555163';
        $userId = 463;

        $clientId = Env::get('tongtongsuo.client_id');
        $clientSecret = Env::get('tongtongsuo.client_secret');
        $domain = Env::get('tongtongsuo.domain');

        $tongtongsuoAccesstoken = Setting::where('name', 'tongtongsuo_accesstoken')->find();
        $tongtongsuoExpirestime = Setting::where('name', 'tongtongsuo_expires_time')->find();

        $headers = ['content-type:application/x-www-form-urlencoded'];
        $options = [
            CURLOPT_HTTPHEADER => $headers
        ];

        if (empty($tongtongsuoAccesstoken->value) or empty($tongtongsuoExpirestime->value)
            or time() - $tongtongsuoExpirestime->updatetime > $tongtongsuoExpirestime->value - 3600 * 24 * 2) {

            $url = $domain . '/oauth2/token';

            $postdata = [
                'clientId' => $clientId,
                'clientSecret' => $clientSecret,
                'username' => Env::get('tongtongsuo.username'),
                'password' => md5(Env::get('tongtongsuo.password')),
            ];

            $res = Http::post($url, http_build_query($postdata), $options);
            $res = json_decode($res, true);

            if (isset($res['access_token'])) {
                $tongtongsuoAccesstoken->value = $res['access_token'];
                $tongtongsuoExpirestime->value = $res['expires_in'];

                $tongtongsuoAccesstoken->save();
                $tongtongsuoExpirestime->save();
            } else {
                return false;
            }
        }

        $startTime = Carbon::parse($startDate);
        $endTime = Carbon::parse($endDate);

        if ($endTime->diffInMinutes($endTime) <= 35) {
            $endTime->addMinutes(30);
        }

        //正式逻辑，下发密码和随机密码
        $postdata = [
            'clientId' => $clientId,
            'accessToken' => $tongtongsuoAccesstoken->value,
            'lockId' => $lockId,
            'receiverUsername' => $phone,
            'keyName' => $lockId . '_' . $startDate,
            'startDate' => $startTime->getTimestampMs(),
            'endDate' => $endTime->getTimestampMs(),
            'createUser' => 2,
            'date' => Carbon::now()->getTimestampMs()
        ];

        $blueKeyId = '';
        $randKeyId = '';
        $randKeyPwd = '';
        $lockData = '';

        $url = $domain . '/v3/key/send';

        $res = Http::post($url, http_build_query($postdata), $options);
        Log::write([
            'params' => $postdata,
            'respnonse' => $res,
        ], 'tongtongsuo_add_password_record', true);

        $res = json_decode($res, true);

        if (!isset($res['keyId'])) {
            Log::write($res, 'tongtongsuo_add_password');
            return false;
        } else {
            $blueKeyId = $res['keyId'];
        }

        $postdata = [
            'clientId' => $clientId,
            'accessToken' => $tongtongsuoAccesstoken->value,
            'lockId' => $lockId,
            'keyboardPwdType' => 3,
            'startDate' => $startTime->getTimestampMs(),
            'endDate' => $endTime->getTimestampMs(),
            'date' => Carbon::now()->getTimestampMs()
        ];

        $url = $domain . '/v3/keyboardPwd/get';

        $res = Http::post($url, http_build_query($postdata), $options);

        Log::write([
            'params' => $postdata,
            'respnonse' => $res,
        ], 'tongtongsuo_add_password_record', true);

        $res = json_decode($res, true);


        if (!isset($res['keyboardPwdId'])) {
            Log::record($res, 'tongtongsuo_add_password');
            return false;
        } else {
            $randKeyId = $res['keyboardPwdId'];
            $randKeyPwd = $res['keyboardPwd'];
        }

        //用户模拟登录和得到蓝牙锁的lockdata
//        if (!$user->isTongTongSuoUser()) {
//            Third::create([
//                'user_id' => $user->id,
//                'platform' => Third::PLATFORM_TONGTONGSUO,
//                'username' => $user->mobile,
//            ]);
//        }

        $third = Third::where('user_id', $userId)->where('platform', Third::PLATFORM_TONGTONGSUO)->find();
        if (empty($third->access_token)
            or time() - $third->updatetime > $third->expires_in - 3600 * 24 * 2) {
            $url = $domain . '/oauth2/token';
            $postdata = [
                'clientId' => $clientId,
                'clientSecret' => $clientSecret,
                'username' => $phone,
                'password' => md5(substr($phone, 5)),
            ];
            $res = Http::post($url, http_build_query($postdata), $options);
            $res = json_decode($res, true);

            if (isset($res['access_token'])) {
                $third->access_token = $res['access_token'];
                $third->expires_in = $res['expires_in'];

                $third->save();
            } else {
                Log::record($res, 'tongtongsuo_add_password');
                return false;
            }
        }

        //得到单把钥匙
        $url = $domain . '/v3/key/get';
        $res = Http::get($url, [
            'clientId' => $clientId,
            'accessToken' => $third->access_token,
            'lockId' => $lockId,
            'date' => Carbon::now()->getTimestampMs(),
        ]);
        $res = json_decode($res, true);

        if (isset($res['lockData'])) {
            $lockData = $res['lockData'];
        } else {
            Log::record($res, 'tongtongsuo_add_password');
            return false;
        }

        return [
            'blue_key_id' => $blueKeyId,
            'blue_lock_data' => $lockData,
            'rand_key_id' => $randKeyId,
            'rand_key_pwd' => $randKeyPwd,
        ];
    }



}
